package com.petalsgroup.petals.service.discuss.impl;

import com.petalsgroup.petals.dao.discuss.DiscussDao;
import com.petalsgroup.petals.dao.discuss.impl.DiscussDaoImpl;
import com.petalsgroup.petals.dao.user.UserDao;
import com.petalsgroup.petals.dao.user.impl.UserDaoImpl;
import com.petalsgroup.petals.pojo.DiscussDO;
import com.petalsgroup.petals.pojo.DiscussVO;
import com.petalsgroup.petals.service.discuss.DiscussService;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class DiscussServiceImpl implements DiscussService {
    private DiscussDao discussDao = new DiscussDaoImpl();
    private UserDao userDao = new UserDaoImpl();

    @Override
    public List<DiscussVO> listDiscussByAid(int aid) {
        return getDiscussVO(discussDao.listDiscussByAid(aid));
    }

    @Override
    public List<DiscussVO> listDiscussByPreId(int preId) {
        return getDiscussVO(discussDao.listDiscussByPreId(preId));
    }

    @Override
    public boolean insertDiscuss(DiscussDO discuss) {
        if (discussDao.insertDiscuss(discuss) == 1) {
            return true;
        }
        return false;
    }

    @Override
    public boolean updateDiscuss(DiscussDO discuss) {
        if (discussDao.updateDiscuss(discuss) == 1) {
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteDiscuss(int did) {
        List<Integer> deleteList = new ArrayList<>();
        deleteList.add(did);
        getDeleteId(deleteList, did);
        for (Integer id : deleteList) {
            if (discussDao.deleteDiscuss(id) != 1) {
                return false;
            }
        }
        return true;
    }

    private void getDeleteId(List deleteList, int did) {
        List<Integer> temp = discussDao.listDeleteDiscuss(did);
        if (temp == null) {
            return;
        } else {
            deleteList.addAll(temp);
            for (Integer id : temp) {
                getDeleteId(deleteList, id);
            }
        }
    }

    private List<DiscussVO> getDiscussVO(List<DiscussDO> dds) {
        if (dds ==  null) {
            return null;
        }
        List<DiscussVO> list = new ArrayList<>(dds.size());
        for (DiscussDO dd : dds) {
            DiscussVO discuss = new DiscussVO();
            discuss.setDiscuss(dd);
            discuss.setUname(userDao.getNameByUid(dd.getUid()));
            list.add(discuss);
        }
        return list;
    }
}
